const appendStyle = require("../tools/appendStyle.js");
const execTimeout = require("../tools/execTimeout.js");
const fs = require("fs");
const path = require("path");
appendStyle(``);

let canvas;
function Pictrue() {
  this.canvas = canvas = canvas || document.createElement("canvas");
  this.ctx = canvas.getContext('2d');
  this.cacheList = [];
  this.cacheImg = {};
  // document.body.appendChild(canvas);
}
function sumOfArr (arr) {
  let sum = 0;
  arr.forEach(num => sum += num);
  return sum;
}
function aviOfArr(arr) {
  return Math.round(sumOfArr (arr) / arr.length);
}
Pictrue.prototype.makeEl = function (type) {
  const img = document.createElement("img");
  const {cacheList, cacheImg, ctx} = this;
  img.onload = function () {
    if (cacheImg[img.src]) {
      currentImgAviColor = cacheImg[img.src];
    } else {
      const {width, height} = img;
      canvas.width = width/3;
      canvas.height = height/3;
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      const getImageData = ctx.getImageData(0,0,canvas.width, canvas.height);
      const result = [[], [], [], []];
      getImageData.data.forEach((color, index) =>{
        result[index%4].push(color);
      });
      cacheImg[img.src] = currentImgAviColor = [
        aviOfArr(result[0]), aviOfArr(result[1]), aviOfArr(result[2]), aviOfArr(result[3])
      ];
    }
    const [r, g, b, a] = currentImgAviColor
    // document.querySelector(".fill-color").innerHTML
    // document.querySelector(".fill-color").style = `background-color: rgba(${r}, ${g}, ${b}, ${a});`
    img.src = "";
    cacheList.push(img);
  };
  return img;
};

Pictrue.prototype.load = function (url) {
  if (!url) return;
  const img = this.cacheList.shift() || this.makeEl();
  img.src = `./img/${url}`;
};
module.exports = new Pictrue();
